package org.budo.warehouse.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.budo.graph.annotation.SpringGraph;
import org.budo.support.javax.sql.util.JdbcUtil;
import org.budo.support.lang.util.NumberUtil;
import org.budo.warehouse.service.api.IDataNodeService;
import org.budo.warehouse.service.api.ServiceDynamicBeanProvider;
import org.budo.warehouse.service.entity.DataNode;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.rpc.service.GenericException;
import com.alibaba.dubbo.rpc.service.GenericService;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Slf4j
@Getter
@Setter
@Service("platformWarehouseQueryService")
public class PlatformWarehouseQueryServiceImpl implements GenericService {
    /**
     * 指定走哪个库查询
     */
    @Value("${platformWarehouseQueryService.dataNodeId}")
    private Object dataNodeId;

    @Resource
    private IDataNodeService dataNodeService;

    @Resource
    private ServiceDynamicBeanProvider serviceDynamicBeanProvider;

    @SpringGraph
    @Override
    public Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException {
        if ("query".equals(method)) {
            String sql = (String) args[0];
            Object[] parameters = (Object[]) args[1];

            PlatformWarehouseQueryServiceImpl _this = (PlatformWarehouseQueryServiceImpl) AopContext.currentProxy();
            return _this.query(sql, parameters);
        }

        log.warn("#47 method=" + method + ", parameterTypes=" + Arrays.toString(parameterTypes) + ", args=" + Arrays.toString(args));
        return null;
    }

    @SpringGraph
    public List<Map<String, Object>> query(String sql, Object[] parameters) {
        if (null == this.getDataNodeId() || !NumberUtil.isInteger(this.getDataNodeId())) {
            log.error("#65 query, sql=" + sql + ", dataNodeId=" + this.getDataNodeId());
            return null;
        }

        Integer dataNodeId = NumberUtil.toInteger(this.getDataNodeId());
        DataNode dataNode = dataNodeService.findByIdCached(dataNodeId);
        DataSource dataSource = serviceDynamicBeanProvider.dataSource(dataNode);
        return JdbcUtil.executeQuery(dataSource, sql, parameters);
    }
}